package com.daykw.douyin.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.DesiredCapabilities;

import com.google.common.collect.Lists;

public class HttpBase {

	private static Logger logger = Logger.getLogger(HttpBase.class);
	private static final java.util.Random RANDOM = new java.util.Random();
	public static String FIREFOX_PATH = System.getProperty("user.dir") + File.separator + "Mozilla Firefox"
			+ File.separator + "firefox.exe";
	public static String PHANTOMJS_PATH = System.getProperty("user.dir") + File.separator + "phantomjs-2.1.1-windows"
			+ File.separator + "bin" + File.separator + "phantomjs.exe";
	public static String GOOGLE_PATH = System.getProperty("user.dir") + File.separator + "chromedriver.exe";
	public static String FIREFOX_DRIVER = System.getProperty("user.dir") + File.separator + "geckodriver32.exe";
	protected static DesiredCapabilities fCaps;
	static {

	}

	public WebDriver getFirefox() throws IOException {
		WebDriver fDriver = null;
		try {
			FirefoxProfile ffProfile = new FirefoxProfile();
			// Prepare capabilities
			System.setProperty("webdriver.firefox.bin", FIREFOX_PATH);
			System.setProperty("webdriver.firefox.marionette", FIREFOX_DRIVER);
//			ffProfile.setPreference("permissions.default.image", 2);
//			fCaps = new DesiredCapabilities();
//			fCaps.setJavascriptEnabled(true);
//			fCaps.setCapability("takesScreenshot", false);

//			fCaps.setCapability(FirefoxDriver.PROFILE, ffProfile);
			fDriver = new FirefoxDriver();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fDriver;
	}

	public WebDriver getNewFirefox() throws IOException {
		WebDriver fDriver = null;
		try {
			System.setProperty("webdriver.gecko.driver", FIREFOX_DRIVER);
			System.setProperty("webdriver.firefox.bin", FIREFOX_PATH);
			fDriver = new FirefoxDriver();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return fDriver;
	}

	public WebDriver getChrome() throws IOException {
		WebDriver driver = null;
		try {
			String chromebin = System.getProperty("user.dir") + File.separator + "ChromePortable" + File.separator
					+ "ChromePortable.exe";// chrome启动文件路径

			/* 设定 chrome启动文件的位置, 若未设定则取默认安装目录的 chrome */
			System.setProperty("webdriver.chrome.bin", chromebin);
			/* 设定 chrome webdirver 的位置 ,若未设定则从path变量读取 */
			System.setProperty("webdriver.chrome.driver", GOOGLE_PATH);
			driver = new ChromeDriver();
			return driver;
			// ChromeDriverService service = new
			// ChromeDriverService.Builder().usingDriverExecutable(new File(GOOGLE_PATH))
			// .usingAnyFreePort().build();
			// WebDriver driver = new ChromeDriver(service);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return driver;
	}

	public static String XD_ORDER = "ZF20181260473u15OkA";

	public static String XD_SCERT = "2e541abf6e0d4b4d9ac4cc67ae5efeed";

	public static String XD_PROXY_IP = "139.199.27.218";
	public static Integer XD_PROXY_PORT = 23128;
	public static String XD_PROXY_NAME = "uh2imyoifv";
	public static String XD_PROXY_PWD = "hpcnfxht54";

	public static String authHeader() {

		int timestamp = (int) (new Date().getTime() / 1000);
		// 拼装签名字符串
		String planText = String.format("orderno=%s,secret=%s,timestamp=%d", XD_ORDER, XD_SCERT, timestamp);

		// 计算签名
		String sign = org.apache.commons.codec.digest.DigestUtils.md5Hex(planText).toUpperCase();

		// 拼装请求头Proxy-Authorization的值
		String authHeader = String.format("sign=%s&orderno=%s&timestamp=%d", sign, XD_ORDER, timestamp);
		return authHeader;
	}

	public String fget(String url, String charset, Map<String, String> header, boolean isproxy) throws Exception {
		CustomGetMethod getMethod = new CustomGetMethod(url);

		try {
			HttpClient client = getClient(charset);

			if (isproxy) {

				String host = "forward.xdaili.cn";
				Integer port = 80;

				client.getHostConfiguration().setProxy(host, port);
				getMethod.setRequestHeader("Proxy-Authorization", authHeader());
			}
			/** header */
			// "User-Agent","Mozilla/5.0 /Windows; U; Windows NT 4.1; de;
			// rv:1.9.1.5) Gecko/20091102 Firefox/3.0"
			// getMethod.setRequestHeader(header);
			getMethod.setRequestHeader("User-Agent",
					"Mozilla/5.0 (Windows NT " + (RANDOM.nextInt(5) + 1) + ".1) AppleWebKit/"
							+ (RANDOM.nextInt(537) + 1) + "." + (RANDOM.nextInt(11) + 1)
							+ " (KHTML, like Gecko) Chrome/" + (RANDOM.nextInt(23) + 1) + ".0."
							+ (RANDOM.nextInt(1271) + 1) + "." + (RANDOM.nextInt(95) + 1) + " Safari/"
							+ (RANDOM.nextInt(537) + 1) + "." + (RANDOM.nextInt(11) + 1) + "");
			getMethod.setRequestHeader("Accept-Encoding", "gzip,deflate,sdch");

			if (header != null && !header.isEmpty()) {
				Set<String> keys = header.keySet();
				for (String key : keys) {
					getMethod.setRequestHeader(key, header.get(key));
				}
			}

			int statusCode = client.executeMethod(getMethod);// 回车——出拳！
			if (statusCode == 200) {
				// getResponseBodyAsString
				String result = getMethod.getResponseBodyAsString();
				if (result.toString().contains(
						"Authentication failed either because credentials were not provided or they could not be validated")
						|| result.toString().contains("You are being redirected to the authentication virtual host.")
						|| result.toString().contains("You are being redirected to the authentication virtual host.")) {

				}
				return result;
			} else {

				// logger.error("请求错误,status code is[" + statusCode + "]");
				return "404";
			}

		} catch (java.net.ConnectException e) {

			return "fail";

		} catch (java.net.SocketTimeoutException e) {

			return "fail";

		} catch (java.net.SocketException e) {

			return "fail";

		} catch (org.apache.commons.httpclient.ConnectTimeoutException e) {

			return "fail";

		} catch (javax.net.ssl.SSLHandshakeException e) {

			return "fail";

		} catch (Exception e) {

			return "fail";

		} finally {
			getMethod.abort();

			getMethod.releaseConnection();
		}

	}
	public String post(String url, Map<String, String> header, Map<String, String> data) {

		try {
			CloseableHttpClient closeHttpClient = HttpClients.createDefault();
			CloseableHttpResponse httpResponse = null;

			RequestConfig config = null;

		
			// getMethod.setRequestHeader("Proxy-Authorization", authHeader());

		
			config = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).build();

			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(config);

			if (header != null) {
				Set<String> keys = header.keySet();
				for (String key : keys) {

					httpPost.setHeader(key, header.get(key));

				}
			}

			List<NameValuePair> params = Lists.newArrayList();

			if (data != null) {
				Set<String> set = data.keySet();
				for (String key : set) {

					String content = data.get(key);
					params.add(new BasicNameValuePair(key, content));
				}
			}

			// 转换参数并设置编码格式
			httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
			// 执行Post请求 得到Response对象
			httpResponse = closeHttpClient.execute(httpPost);
			// httpResponse.getStatusLine() 响应头信息
			System.out.println(httpResponse.getStatusLine());

			int statusCode = httpResponse.getStatusLine().getStatusCode();

			if (statusCode == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				return result;
			} else if (statusCode == 301) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				return result;
			} else if (statusCode == 400) {
				return "400";
			} else if (statusCode == 500) {
				return "500";
			} else if (statusCode == 502) {
				return "502";
			} else {
				return "fail";
			}

		} catch (Exception e) {

			return "fail";

		}

	}
	public String fpost(String url, String charset, Map<String, String> header, Map<String, String> data) {

		try {
			CloseableHttpClient closeHttpClient = HttpClients.createDefault();
			CloseableHttpResponse httpResponse = null;

			RequestConfig config = null;

			String host = "forward.xdaili.cn";
			Integer port = 80;
			header.put("Proxy-Authorization", authHeader());
			// getMethod.setRequestHeader("Proxy-Authorization", authHeader());

			HttpHost proxy = new HttpHost(host, port, "http");
			config = RequestConfig.custom().setSocketTimeout(4000).setConnectTimeout(4000).setProxy(proxy).build();

			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(config);

			if (header != null) {
				Set<String> keys = header.keySet();
				for (String key : keys) {

					httpPost.setHeader(key, header.get(key));

				}
			}

			List<NameValuePair> params = Lists.newArrayList();

			if (data != null) {
				Set<String> set = data.keySet();
				for (String key : set) {

					String content = data.get(key);
					params.add(new BasicNameValuePair(key, content));
				}
			}

			// 转换参数并设置编码格式
			httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
			// 执行Post请求 得到Response对象
			httpResponse = closeHttpClient.execute(httpPost);
			// httpResponse.getStatusLine() 响应头信息
			System.out.println(httpResponse.getStatusLine());

			int statusCode = httpResponse.getStatusLine().getStatusCode();

			if (statusCode == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				return result;
			} else if (statusCode == 400) {
				return "400";
			} else if (statusCode == 500) {
				return "500";
			} else if (statusCode == 502) {
				return "502";
			} else {
				return "fail";
			}

		} catch (Exception e) {

			return "fail";

		}

	}

	public String fget(String url, Map<String, String> header, boolean isproxy) throws Exception {
		CustomGetMethod getMethod = new CustomGetMethod(url);

		try {
			HttpClient client = getClient("utf-8");

			if (isproxy) {

				String host = "forward.xdaili.cn";
				Integer port = 80;

				client.getHostConfiguration().setProxy(host, port);
				getMethod.setRequestHeader("Proxy-Authorization", authHeader());
			}
			/** header */
			// "User-Agent","Mozilla/5.0 /Windows; U; Windows NT 4.1; de;
			// rv:1.9.1.5) Gecko/20091102 Firefox/3.0"
			// getMethod.setRequestHeader(header);
			getMethod.setRequestHeader("User-Agent",
					"Mozilla/5.0 (Windows NT " + (RANDOM.nextInt(5) + 1) + ".1) AppleWebKit/"
							+ (RANDOM.nextInt(537) + 1) + "." + (RANDOM.nextInt(11) + 1)
							+ " (KHTML, like Gecko) Chrome/" + (RANDOM.nextInt(23) + 1) + ".0."
							+ (RANDOM.nextInt(1271) + 1) + "." + (RANDOM.nextInt(95) + 1) + " Safari/"
							+ (RANDOM.nextInt(537) + 1) + "." + (RANDOM.nextInt(11) + 1) + "");
			getMethod.setRequestHeader("Accept-Encoding", "gzip,deflate,sdch");

			if (header != null && !header.isEmpty()) {
				Set<String> keys = header.keySet();
				for (String key : keys) {
					getMethod.setRequestHeader(key, header.get(key));
				}
			}

			int statusCode = client.executeMethod(getMethod);// 回车——出拳！
			if (statusCode == 200) {
				// getResponseBodyAsString
				String result = getMethod.getResponseBodyAsString();
				if (result.toString().contains(
						"Authentication failed either because credentials were not provided or they could not be validated")
						|| result.toString().contains("You are being redirected to the authentication virtual host.")
						|| result.toString().contains("You are being redirected to the authentication virtual host.")) {

				}
				return result;
			} else if (statusCode == 400) {
				return "400";
			} else if (statusCode == 500) {
				return "500";
			} else if (statusCode == 502) {
				return "fail";
			} else {
				return "fail";
			}

		} catch (java.net.ConnectException e) {

			return "fail";

		} catch (java.net.SocketTimeoutException e) {

			return "fail";

		} catch (java.net.SocketException e) {

			return "fail";

		} catch (org.apache.commons.httpclient.ConnectTimeoutException e) {

			return "fail";

		} catch (javax.net.ssl.SSLHandshakeException e) {

			return "fail";

		} catch (Exception e) {

			return "fail";

		} finally {
			getMethod.abort();

			getMethod.releaseConnection();
		}

	}

	public void pget(String url) {
		try {
			// 设置代理HttpHost
			HttpHost proxy = new HttpHost(XD_PROXY_IP, XD_PROXY_PORT, "http");

			// 设置要访问的HttpHost,即是目标站点的HttpHost
			HttpHost target = new HttpHost(url, 80);

			// 设置认证
			CredentialsProvider provider = new BasicCredentialsProvider();

			provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(XD_PROXY_NAME, XD_PROXY_PWD));

			CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();

			RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

			HttpGet httpGet = new HttpGet("/");

			httpGet.setConfig(config);

			CloseableHttpResponse resp = httpClient.execute(target, httpGet);
			System.out.println(resp.getStatusLine().getStatusCode());
			String result = EntityUtils.toString(resp.getEntity());
			System.out.println(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public synchronized Response httpGet(String url, Map<String, String> headers) throws Exception {
		HttpClient client = getClient("utf-8");
		CustomGetMethod getMethod = new CustomGetMethod(url);// 创建一个get方法，类似在浏览器地址栏中输入一个地址
		if (headers != null) {
			Set<String> keys = headers.keySet();
			for (String k : keys) {
				getMethod.setRequestHeader(k, headers.get(k));
			}
		}
		getMethod.setRequestHeader("accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		getMethod.setRequestHeader("Accept-Encoding", "gzip, deflate, sdch");
		getMethod.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8");
		getMethod.setRequestHeader("Upgrade-Insecure-Requests", "1");
		getMethod.setRequestHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");

		int statusCode = client.executeMethod(getMethod);// 回车——出拳！

		Header[] _map = getMethod.getResponseHeaders();
		Map<String, String> map = new HashMap<String, String>();
		for (Header h : _map) {
			map.put(h.getName(), h.getValue());
		}
		if (statusCode == 200) {
			String body = getMethod.getResponseBodyAsString();
			getMethod.releaseConnection();
			Response r = new Response();
			r.setResult(body);
			r.setHeader(map);
			r.setStatus(statusCode);
			getMethod.abort();
			getMethod.releaseConnection();// 释放，记得收拳哦
			return r;
		}
		if (statusCode == 500) {
			String body = getMethod.getResponseBodyAsString();
			getMethod.releaseConnection();
			if (StringUtils.isNotEmpty(body)) {
				Response r = new Response();
				r.setResult(body);
				r.setHeader(map);
				r.setStatus(statusCode);
				getMethod.abort();
				getMethod.releaseConnection();// 释放，记得收拳哦
				return r;
			}
			getMethod.abort();
			getMethod.releaseConnection();// 释放，记得收拳哦
			throw new java.net.ConnectException("请求错误,status code is[" + statusCode + "]");
		}
		String body = getMethod.getResponseBodyAsString();
		Response r = new Response();
		r.setResult(body);
		r.setHeader(map);
		r.setStatus(statusCode);
		getMethod.abort();
		getMethod.releaseConnection();// 释放，记得收拳哦
		return r;
	}

	public synchronized String get(String url, Map<String, String> headers) throws Exception {
		HttpClient client = getClient("utf-8");
		CustomGetMethod getMethod = new CustomGetMethod(url);// 创建一个get方法，类似在浏览器地址栏中输入一个地址
		if (headers != null) {
			Set<String> keys = headers.keySet();
			for (String k : keys) {
				getMethod.setRequestHeader(k, headers.get(k));
			}
		}
//		getMethod.setRequestHeader("accept",
//				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//		getMethod.setRequestHeader("Accept-Encoding", "gzip, deflate, sdch");
//		getMethod.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8");
//		getMethod.setRequestHeader("Upgrade-Insecure-Requests", "1");
		getMethod.setRequestHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");

		int statusCode = client.executeMethod(getMethod);// 回车——出拳！

		Header[] _map = getMethod.getResponseHeaders();
		Map<String, String> map = new HashMap<String, String>();
		for (Header h : _map) {
			map.put(h.getName(), h.getValue());
		}
		if (statusCode == 200) {
			String body = getMethod.getResponseBodyAsString();
			getMethod.releaseConnection();

			getMethod.abort();
			getMethod.releaseConnection();// 释放，记得收拳哦
			return body;
		}
		if (statusCode == 302) {
			String body = getMethod.getResponseBodyAsString();
			getMethod.releaseConnection();

			getMethod.abort();
			getMethod.releaseConnection();// 释放，记得收拳哦
			return "302";
		}
		if (statusCode == 500) {
			String body = getMethod.getResponseBodyAsString();
			getMethod.releaseConnection();
			if (StringUtils.isNotEmpty(body)) {

				getMethod.abort();
				getMethod.releaseConnection();// 释放，记得收拳哦
				return body;
			}
			getMethod.abort();
			getMethod.releaseConnection();// 释放，记得收拳哦
			throw new java.net.ConnectException("请求错误,status code is[" + statusCode + "]");
		}
		String body = getMethod.getResponseBodyAsString();

		getMethod.abort();
		getMethod.releaseConnection();// 释放，记得收拳哦
		return body;
	}

	private HttpClient getClient(String charset) {
		MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
		Integer MAX_TIME_OUT = 5000;
		// Integer MAX_IDLE_TIME_OUT = 60000;
		Integer MAX_CONN = 5000;
		connectionManager.closeIdleConnections(MAX_TIME_OUT);
		connectionManager.getParams().setParameter("http.connection-manager.max-total", MAX_CONN);
		HttpClient client = new HttpClient(connectionManager);
		HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
		params.setConnectionTimeout(5000);
		params.setSoTimeout(5000);
		params.setDefaultMaxConnectionsPerHost(500);
		params.setMaxTotalConnections(500);
		params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

		HttpClientParams hcp = client.getParams();
		// hcp.setParameter("http.connection.timeout", 15 * 1000);
		// hcp.setParameter("http.connection-manager.timeout", 15 * 1000);
		hcp.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
		hcp.setAuthenticationPreemptive(true);
		return client;
	}

	public String getResponseBodyAsString(GetMethod getMethod) throws IOException {

		GZIPInputStream gzin;

		if (getMethod.getResponseBody() != null || getMethod.getResponseBodyAsStream() != null) {

			if (getMethod.getResponseHeader("Content-Encoding") != null

					&& getMethod.getResponseHeader("Content-Encoding").getValue().toLowerCase().indexOf("gzip") > -1) {

				// For GZip response

				InputStream is = getMethod.getResponseBodyAsStream();

				gzin = new GZIPInputStream(is);

				InputStreamReader isr = new InputStreamReader(gzin, getMethod.getResponseCharSet());

				java.io.BufferedReader br = new java.io.BufferedReader(isr);

				StringBuffer sb = new StringBuffer();

				String tempbf;

				while ((tempbf = br.readLine()) != null) {
					sb.append(tempbf);
					sb.append("\r\n");
				}
				isr.close();
				gzin.close();
				return sb.toString();
			} else {
				// For deflate response
				return getMethod.getResponseBodyAsString();
			}
		} else {
			return null;
		}

	}

	public String enCodetoString(final HttpEntity entity, final String defaultCharset)
			throws IOException, ParseException {
		return enCodetoStringDo(entity, defaultCharset != null ? Charset.forName(defaultCharset) : null);
	}

	public String enCodetoStringDo(final HttpEntity entity, Charset defaultCharset) throws IOException, ParseException {
		if (entity == null) {
			throw new IllegalArgumentException("HTTP entity may not be null");
		}
		InputStream instream = entity.getContent();
		if (instream == null) {
			return null;
		}
		try {
			if (entity.getContentLength() > Integer.MAX_VALUE) {
				throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
			}
			int i = (int) entity.getContentLength();
			if (i < 0) {
				i = 4096;
			}
			Charset charset = null;
			try {
				// ContentType contentType = ContentType.get(entity);
				// if (contentType != null) {
				// charset = contentType.getCharset();
				// }
			} catch (final UnsupportedCharsetException ex) {
				throw new UnsupportedEncodingException(ex.getMessage());
			}
			if (charset == null) {
				charset = defaultCharset;
			}
			if (charset == null) {
				charset = HTTP.DEF_CONTENT_CHARSET;
			}
			Reader reader = new InputStreamReader(instream, charset);
			CharArrayBuffer buffer = new CharArrayBuffer(i);
			char[] tmp = new char[1024];
			int l;
			while ((l = reader.read(tmp)) != -1) {
				buffer.append(tmp, 0, l);
			}
			return buffer.toString();
		} finally {
			instream.close();
		}
	}

	public synchronized String http(String url, Map<String, String> headers) throws Exception {
		URL u = new URL(url);
		// 创建HttpsURLConnection对象，并设置其SSLSocketFactory对象
		URLConnection.setDefaultAllowUserInteraction(true);
		URLConnection httpsConn = u.openConnection();

		Set<String> keys = headers.keySet();
		for (String k : keys) {
			httpsConn.setRequestProperty(k, headers.get(k));
		}

		// 取得该连接的输入流，以读取响应内容
		BufferedReader insr = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));

		// 读取服务器的响应内容并显示
		StringBuffer sb = new StringBuffer();
		String s;
		while ((s = insr.readLine()) != null) {
			sb.append(s + "\n");
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		HttpBase http = new HttpBase();
		try {
			// 55a26cbc-5d13-45bb-9b96-97276d648b92
			http.pget("m.itslaw.com/mobile/judgements/judgement/55a26cbc-5d13-45bb-9b96-97276d648b92");

//			WebDriver wb = http.getFirefox();
//			String url = "http://wenshu.court.gov.cn/list/list/?sorttype=1&conditions=searchWord+++2018-10-09%20TO%202018-10-10+%E4%B8%8A%E4%BC%A0%E6%97%A5%E6%9C%9F:2018-10-09%20TO%202018-10-10";
//			wb.get(url);
//
//			WebDriverWait wait = new WebDriverWait(wb, 20);
//			wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.dataItem")));
//			// WebElement element = wb.findElement(By.cssSelector("div.dataItem"));
//			String html = wb.getPageSource();
//			System.out.println(html);
//			JavascriptExecutor js = (JavascriptExecutor) wb;
//			// 获取网页高度，用于滚动到底部，防止仅加载一部分数据
//
//			wb.manage().window().maximize();
//			try {
//				js.executeScript("scrollTo(0,30000)");
//			} catch (Exception E) {
//
//			}
//			try {
//				TimeUnit.SECONDS.sleep(1);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//
//			WebDriverWait wait1 = new WebDriverWait(wb, 5);
//			wait1.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("a.next")));
//			wb.findElement(By.cssSelector("a.next")).click();
//			wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.dataItem")));
//			html = wb.getPageSource();
			// System.out.println(html);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void getPost() {
		try {
			// WebDriverPool wp = new WebDriverPool();
			Map<String, String> headers = new HashMap<String, String>();

			headers.put("Accept", "*/*");
			headers.put("Accept-Encoding", "gzip, deflate");
			headers.put("Accept-Language", "zh-CN,zh;q=0.9");
			headers.put("Connection", "keep-alive");

			headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			headers.put("Cookie",
					"_gscu_2116842793=38967468pt04vc18; Hm_lvt_d2caefee2de09b8a6ea438d74fd98db2=1538967469,1539073253; _gscbrs_2116842793=1; VCode=196613a6-4be7-4f67-92de-aaeda4b31bc6; User=UserName=ebin1983@163.com; _gscs_2116842793=39073253tv9moi15|pv:11; Hm_lpvt_d2caefee2de09b8a6ea438d74fd98db2=1539074225; vjkl5=2f6a199fffa57f601de182bda2f1053e4c3a105a");
			headers.put("Host", "wenshu.court.gov.cn");

			headers.put("Origin", "http://wenshu.court.gov.cn");
			headers.put("Referer",
					"http://wenshu.court.gov.cn/list/list/?sorttype=1&conditions=searchWord+++2018-10-09%20TO%202018-10-10+%E4%B8%8A%E4%BC%A0%E6%97%A5%E6%9C%9F:2018-10-09%20TO%202018-10-10");
			headers.put("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36");
			headers.put("X-Requested-With", "XMLHttpRequest");

			HttpBase http = new HttpBase();
			// for (int i = 39; i <= 825; i++) {
			try {
				// int page = i * 100;
				String url = "http://wenshu.court.gov.cn/List/ListContent";

				// String body =
				// "上传日期:2018-10-09+TO+2018-10-10&Index=1&Page=10&Order=法院层级&Direction=asc&vl5x=9ef522c6a27988f28f120854&number=wens&guid=9211d26f-adc0-21b2173d-d53ac11da4ea";
				Map<String, String> map = new HashMap<String, String>();
				map.put("Param", "上传日期:2018-10-09 TO 2018-10-10");
				map.put("Index", "1");
				map.put("Page", "10");
				map.put("Order", "法院层级");
				map.put("Direction", "asc");
				map.put("vl5x", "f14df0d5158aca41f59a42ac");
				map.put("number", "wens");
				map.put("guid", "392bb5b2-b20a-34fc4a1f-845db3ca57d3");
				//String html = http.post(url, "utf-8", headers, map, false);

				//System.out.println(html);
			} catch (Exception e) {
				// i--;
			}
			// }

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class ProxyAuthenticator extends Authenticator {
	private String user, password;

	public ProxyAuthenticator(String user, String password) {
		this.user = user;
		this.password = password;
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(user, password.toCharArray());
	}

}
